//
//  PassengerViewController.m
//  EasyToo
//
//  Created by Jr Lan on 13-8-26.
//
//

#import "PassengerViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "ConfirmTicketViewController.h"

#define PICKERTICKETTYPETAG 10005
#define PICKERIDENTITYTYPETAG 10006

#define TFTICKETTYPEAG 10007
#define TFIDENTITYTYPETAG 10008

@interface PassengerViewController ()

@end

@implementation PassengerViewController
{
    UIImageView *_imgview;
    UILabel *_infolb;
    
    UITextField *_nameTF;
    
    UITextField *_tickTypeTF;
    UIPickerView *_ticketTypePicker;
    NSArray *_ticketTypeArray;

    UITextField *_idTypeTF;
    UIPickerView *_idTypePicker;
    NSArray *_idTypeArray;
    
    UITextField *_idnumTF;
    
    UIImageView *_imgcontactview;
    UILabel *_infocontactlb;
    
    UITextField *_contactnameTF;
    
    UITextField *_contactphoneTF;
    
    UIButton *_queryBtn;
    
    UIBarButtonItem *_right;
    UIToolbar *_toolBar;
    
    UIAlertView *_baseAlert;
}

- (void) dealloc
{
    [_imgview release];
    [_infolb release];
    [_nameTF release];
    [_tickTypeTF release];
    [_ticketTypePicker release];
    [_ticketTypeArray release];
    [_idTypeTF release];
    [_idTypePicker release];
    [_idTypeArray release];
    [_idnumTF release];
    [_imgcontactview release];
    [_infocontactlb release];
    [_contactnameTF release];
    [_contactphoneTF release];
    [_toolBar release];
    [_right release];
    
    _imgview = nil;
    _infolb = nil;
    _nameTF = nil;
    _tickTypeTF = nil;
    _ticketTypePicker = nil;
    _ticketTypeArray = nil;
    _idTypeTF = nil;
    _idTypePicker = nil;
    _idTypeArray = nil;
    _idnumTF = nil;
    _imgcontactview = nil;
    _infocontactlb = nil;
    _contactnameTF = nil;
    _contactphoneTF = nil;
    _toolBar = nil;
    _right = nil;
    
    [super dealloc];
}


@synthesize yearType;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    //初始化视图
    [self init_view];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void) init_view
{
    //定义title
    self.title = @"机票";
    //加载背影
     [self.view setBackgroundColor:BackgroundColor];
    
    
    int width = [DeviceUtil getScreenWidth];
    int heigth = self.view.frame.size.height;
    
    UIScrollView *myscrollview = [[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, width, heigth)]autorelease];
    myscrollview.directionalLockEnabled = YES; //只能一个方向滑动
    myscrollview.pagingEnabled = NO; //是否翻页
    myscrollview.backgroundColor = [UIColor whiteColor];
    myscrollview.showsVerticalScrollIndicator =YES; //垂直方向的滚动指示
    myscrollview.indicatorStyle = UIScrollViewIndicatorStyleWhite;//滚动指示的风格
    myscrollview.showsHorizontalScrollIndicator = NO;//水平方向的滚动指示
    myscrollview.delegate = self;
    CGSize newSize = CGSizeMake(width, 1000);
    [myscrollview setContentSize:newSize];
    
    UIControl *control = [[[UIControl alloc] initWithFrame:myscrollview.frame] autorelease];
    [myscrollview addSubview:control];
    [control addTarget:self action:@selector(onBackgroudTouch) forControlEvents:UIControlEventTouchDown];

    
    //填写乘机人信息
    _imgview = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"4.png"]];
    _imgview.frame = CGRectMake(20, 20, 20, 20);
    [myscrollview addSubview:_imgview];
    
    _infolb = [[UILabel alloc]initWithFrame:CGRectMake(50, 20, 280, 20)];
    _infolb.text = @"填写乘机人信息";
    _infolb.font = [UIFont systemFontOfSize:15];
    _infolb.adjustsFontSizeToFitWidth = YES;
    _infolb.backgroundColor = [UIColor clearColor];
    [myscrollview addSubview:_infolb];
    
    //姓名
    _nameTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 50, 280, 50)];
    _nameTF.placeholder = @"乘机人姓名";
    _nameTF.font = [UIFont fontWithName:@"Arial" size:18.0f];
    _nameTF.textColor = [UIColor blackColor];
    _nameTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _nameTF.borderStyle = UITextBorderStyleRoundedRect;
    _nameTF.delegate = self ;
    _nameTF.returnKeyType =UIReturnKeyDone;
    _nameTF.layer.borderColor = [UIColor grayColor].CGColor;
    _nameTF.layer.borderWidth = 1 ;
    _nameTF.layer.cornerRadius = 10 ;
    [myscrollview addSubview:_nameTF];
    
    //票务类型
    [self init_view_type:myscrollview];
    
    //身份证类型
    [self init_view_id:myscrollview];
    
    //证件号码
    _idnumTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 230, 280, 50)];
    _idnumTF.placeholder = @"证件号码";
    _idnumTF.font = [UIFont fontWithName:@"Arial" size:18.0f];
    _idnumTF.textColor = [UIColor blackColor];
    _idnumTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _idnumTF.borderStyle = UITextBorderStyleRoundedRect;
    _idnumTF.delegate = self ;
    _idnumTF.returnKeyType =UIReturnKeyDone;
    _idnumTF.layer.borderColor = [UIColor grayColor].CGColor;
    _idnumTF.layer.borderWidth = 1 ;
    _idnumTF.layer.cornerRadius = 10 ;
    [myscrollview addSubview:_idnumTF];
    
    //联系人
    if ([self.userArray count] == 0) {
        [self addContact:myscrollview];
    }
    
    //订票
    _queryBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    if ([self.userArray count] == 0) {
        _queryBtn.frame = CGRectMake(20, 450, 280, 40);
    } else {
        _queryBtn.frame = CGRectMake(20, 290, 280, 40);
    }
    [_queryBtn setBackgroundImage:[UIImage imageNamed:@"xyb"] forState:UIControlStateNormal];
    [_queryBtn setTitle:@"订购" forState:UIControlStateNormal];
    _queryBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _queryBtn.layer.borderColor = [UIColor grayColor].CGColor;
    _queryBtn.layer.borderWidth = 1 ;
    _queryBtn.layer.cornerRadius = 10 ;
    [myscrollview addSubview:_queryBtn];
    
    //添加button方法
    [_queryBtn addTarget:self action:@selector(queryEvent) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:myscrollview];
}

//联系人
- (void)addContact:(UIScrollView*)myscrollview
{
    //填写联系人信息
    _imgcontactview = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"4.png"]];
    _imgcontactview.frame = CGRectMake(20, 290, 20, 20);
    [myscrollview addSubview:_imgcontactview];
    
    _infocontactlb = [[UILabel alloc]initWithFrame:CGRectMake(50, 290, 280, 30)];
    _infocontactlb.text = @"填写联系人信息";
    _infocontactlb.font = [UIFont systemFontOfSize:15];
    _infocontactlb.adjustsFontSizeToFitWidth = YES;
    _infocontactlb.backgroundColor = [UIColor clearColor];
    [myscrollview addSubview:_infocontactlb];
    
    //联系人姓名
    _contactnameTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 330, 280, 50)];
    _contactnameTF.placeholder = @"联系人姓名";
    _contactnameTF.font = [UIFont fontWithName:@"Arial" size:18.0f];
    _contactnameTF.textColor = [UIColor blackColor];
    _contactnameTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _contactnameTF.borderStyle = UITextBorderStyleRoundedRect;
    _contactnameTF.delegate = self ;
    _contactnameTF.returnKeyType =UIReturnKeyDone;
    _contactnameTF.layer.borderColor = [UIColor grayColor].CGColor;
    _contactnameTF.layer.borderWidth = 1 ;
    _contactnameTF.layer.cornerRadius = 10 ;
    [myscrollview addSubview:_contactnameTF];
    
    //联系人电话
    _contactphoneTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 390, 280, 50)];
    _contactphoneTF.placeholder = @"联系人电话";
    _contactphoneTF.keyboardType = UIKeyboardTypeNumberPad;
    _contactphoneTF.font = [UIFont fontWithName:@"Arial" size:18.0f];
    _contactphoneTF.textColor = [UIColor blackColor];
    _contactphoneTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _contactphoneTF.borderStyle = UITextBorderStyleRoundedRect;
    _contactphoneTF.delegate = self ;
    _contactphoneTF.returnKeyType =UIReturnKeyDone;
    _contactphoneTF.layer.borderColor = [UIColor grayColor].CGColor;
    _contactphoneTF.layer.borderWidth = 1 ;
    _contactphoneTF.layer.cornerRadius = 10 ;
    [myscrollview addSubview:_contactphoneTF];
}

//票务类型
- (void) init_view_type:(UIScrollView*)myscrollview
{
    _tickTypeTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 110, 280, 50)];
    _tickTypeTF.tag = TFTICKETTYPEAG;
    _tickTypeTF.text = @"成人(>12岁)";

    _tickTypeTF.font = [UIFont fontWithName:@"Arial" size:18.0f];
    _tickTypeTF.textColor = [UIColor blackColor];
    _tickTypeTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _tickTypeTF.borderStyle = UITextBorderStyleRoundedRect;
    _tickTypeTF.delegate = self ;
    _tickTypeTF.returnKeyType =UIReturnKeyDone;
    _tickTypeTF.layer.borderColor = [UIColor grayColor].CGColor;
    _tickTypeTF.layer.borderWidth = 1 ;
    _tickTypeTF.layer.cornerRadius = 10 ;
    [myscrollview addSubview:_tickTypeTF];
    
    // 建立 UIToolbar
    _toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    _right = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(cancelstartPicker)];
    
    // 把按鈕加進 UIToolbar
    _toolBar.items = [NSArray arrayWithObject:_right];
    
    _ticketTypeArray = [[NSArray arrayWithObjects:@"成人(>12岁)", @"儿童(2>12岁)", @"婴儿(<2岁)", nil] retain];
    _ticketTypePicker = [[UIPickerView alloc]initWithFrame:CGRectZero];
    _ticketTypePicker.tag = PICKERTICKETTYPETAG;
    _ticketTypePicker.showsSelectionIndicator = YES;
    
    _tickTypeTF.inputAccessoryView = _toolBar;
    _tickTypeTF.delegate = self;
    _ticketTypePicker.delegate = self;
    _ticketTypePicker.dataSource = self;
    _ticketTypePicker.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    _tickTypeTF.inputView = _ticketTypePicker;
}

//身份证类型
- (void)init_view_id:(UIScrollView*)myscrollview
{
    _idTypeTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 170, 280, 50)];
    _idTypeTF.tag = TFIDENTITYTYPETAG;
    _idTypeTF.text = @"身份证";
    _idTypeTF.placeholder = @"身份证";
    
    _idTypeTF.font = [UIFont fontWithName:@"Arial" size:18.0f];
    _idTypeTF.textColor = [UIColor blackColor];
    _idTypeTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    _idTypeTF.borderStyle = UITextBorderStyleRoundedRect;
    _idTypeTF.delegate = self ;
    _idTypeTF.returnKeyType =UIReturnKeyDone;
    _idTypeTF.layer.borderColor = [UIColor grayColor].CGColor;
    _idTypeTF.layer.borderWidth = 1 ;
    _idTypeTF.layer.cornerRadius = 10 ;
    [myscrollview addSubview:_idTypeTF];
    
    // 建立 UIToolbar
    _toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    _right = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(cancelstartPicker)];
    
    // 把按鈕加進 UIToolbar
    _toolBar.items = [NSArray arrayWithObject:_right];
    
    _idTypeArray = [[NSArray arrayWithObjects:@"身份证", @"驾驶证", nil] retain];
    _idTypePicker = [[UIPickerView alloc]initWithFrame:CGRectZero];
    _idTypePicker.tag = TFIDENTITYTYPETAG;
    _idTypePicker.showsSelectionIndicator = YES;
    
    _idTypeTF.inputAccessoryView = _toolBar;
    _idTypeTF.delegate = self;
    _idTypePicker.delegate = self;
    _idTypePicker.dataSource = self;
    _idTypePicker.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    _idTypeTF.inputView = _idTypePicker;

}


//查询事件
- (void)queryEvent
{
    //检测信息是否为空
    if ([_nameTF.text isEqualToString:@""] == YES || [_idnumTF.text isEqualToString:@""] == YES) {
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"信息不完整" message:@"请填写完整信息再提交"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];
    }
    
    else if (([self.userArray count] == 0) && ([_contactnameTF.text isEqualToString:@""] == YES || [_contactphoneTF.text isEqualToString:@""] == YES)){
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"联系人信息不完整" message:@"请填写联系人信息再提交"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];
        
    }
    //判断手机号码格式
    else if (([self.userArray count] == 0) && ([DeviceUtil isMobileNumber:_contactphoneTF.text] == NO)) {
        _baseAlert = [[UIAlertView alloc]  initWithTitle:@"注册出错" message:@"手机号格式出错"  delegate:self cancelButtonTitle:@"返回" otherButtonTitles: nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
        [_baseAlert show];
    }
    
    //转发请求
    else{
        NSString *contactname;
        NSString *contactphone;
        if ([self.userArray count] == 0) {
            contactname = _contactnameTF.text;
            contactphone = _contactphoneTF.text;
        } else {
            NSDictionary *dic = [self.userArray objectAtIndex:0];
            contactname = [dic objectForKey:@"contactname"];
            contactphone = [dic objectForKey:@"contactphone"];
        }
        ConfirmTicketViewController *confirmController = [[ConfirmTicketViewController alloc] init];
        NSDictionary *userDict = [NSDictionary dictionaryWithObjectsAndKeys:_nameTF.text, @"name",
                                                                            _idnumTF.text, @"idnum",
                                                                            [_tickTypeTF.text substringWithRange:NSMakeRange(0, 2)], @"type",
                                                                            contactname, @"contactname",
                                                                            contactphone, @"contactphone", nil];
        NSMutableArray *userInfos = self.userArray;
        [userInfos addObject:userDict];
        confirmController.userArray = userInfos;
        confirmController.orderInfo = self.orderInfo;
        confirmController.startCity = self.startCity;
        confirmController.arriveCity = self.arriveCity;
        confirmController.startDate = self.startDate;
        [self.navigationController pushViewController:confirmController animated:YES];
        [confirmController release];
    }
    
}

- (void) performDismiss: (NSTimer *)timer {
    [_baseAlert dismissWithClickedButtonIndex:0 animated:NO];//important
    [_baseAlert release];
    _baseAlert = NULL;
}

#pragma picker delegate
-(void) cancelstartPicker {
    [_tickTypeTF endEditing:YES];
    [_idTypeTF endEditing:YES];
}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}
-(NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (pickerView.tag == PICKERTICKETTYPETAG) {
        return [_ticketTypeArray count];
    } else {
        return [_idTypeArray count];
    }
}
-(NSString*) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (pickerView.tag == PICKERTICKETTYPETAG) {
        return [_ticketTypeArray objectAtIndex:row];
    } else {
        return [_idTypeArray objectAtIndex:row];
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[[UILabel alloc] init] autorelease];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:[UIFont systemFontOfSize:15]];
    }
    // Fill the label text here
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.tag == TFTICKETTYPEAG) {
        NSInteger row = [_ticketTypePicker selectedRowInComponent:0];
        _tickTypeTF.text = [_ticketTypeArray objectAtIndex:row];
    } else {
        NSInteger row = [_idTypePicker selectedRowInComponent:0];
        _idTypeTF.text = [_idTypeArray objectAtIndex:row];
    }
}



//开始编辑输入框的时候，软键盘出现，执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect frame = textField.frame;
    int offset = frame.origin.y + 32 - (self.view.frame.size.height - 216.0);//键盘高度216
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
    if(offset > 0)
        self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
    
    [UIView commitAnimations];
}


#pragma mark UITextFieldDelegate
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_nameTF resignFirstResponder];
    [_idnumTF resignFirstResponder];
    [_contactnameTF resignFirstResponder];
    [_contactphoneTF resignFirstResponder];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);
    self.view.frame = rect;
    [UIView commitAnimations];
    [textField resignFirstResponder];
    return YES;
}

- (void)onBackgroudTouch
{
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);
    self.view.frame = rect;
    [UIView commitAnimations];
    
    [_nameTF resignFirstResponder];
    [_idnumTF resignFirstResponder];
    [_contactnameTF resignFirstResponder];
    [_contactphoneTF resignFirstResponder];
}


@end


